package com.inputabc.ct.v1.setting;

import com.inputabc.ct.v1.ui.SettingsDialog;
import com.inputabc.ct.v1.util.*;

import java.awt.*;
import java.io.*;
import java.util.Properties;

/**
 * 软件首选项
 *
 * @author gaoweiyi
 */
public class SettingContext {
    public static TextBoxSetting textBoxSetting;
    public static TranslateSetting translateSetting;
    public static KeySetting keySetting = new KeySetting();
    
    // 添加配置文件路径的常量
    public static final String SETTING_CONF = "settings.conf";

    public static void load(String settingFilePath) throws Exception {
        File file = new File(settingFilePath);
        if (file.exists() == false) {
            file.createNewFile();
        }
        Properties p = new Properties();
        p.load(new BufferedReader(new InputStreamReader(new FileInputStream(settingFilePath))));
        textBoxSetting = new TextBoxSetting();
        //设置文本窗体的初始位置
        String textBoxLocationV = p.getProperty("textbox.location","-1,-1");
        Integer[] textBoxLocation = new Integer[2];
        textBoxLocation[0] = Integer.valueOf(textBoxLocationV.split(",")[0]);
        textBoxLocation[1] = Integer.valueOf(textBoxLocationV.split(",")[1]);
        textBoxSetting.setLocation(textBoxLocation);
        // 设置文本窗体的大小
        String textBoxSizeV = p.getProperty("textbox.size", "520x250");
        Integer[] textBoxSize = new Integer[2];
        textBoxSize[0] = Integer.valueOf(textBoxSizeV.split("x")[0]);
        textBoxSize[1] = Integer.valueOf(textBoxSizeV.split("x")[1]);
        textBoxSetting.setSize(textBoxSize);

        // 设置文本框字体大小
        String textBoxFontSizeV = p.getProperty("textbox.font.size", "18");
        TextBoxSetting.FontSetting fontSetting = new TextBoxSetting.FontSetting();
        fontSetting.setSize(Integer.parseInt(textBoxFontSizeV));
        textBoxSetting.setFontSetting(fontSetting);

        // 设置文本框背景色
        String textBoxBackgroundColorV = p.getProperty("textbox.background.color", "0,0,0");
        TextBoxSetting.BackgroundSetting backgroundSetting = new TextBoxSetting.BackgroundSetting();
        String[] colorSplits = textBoxBackgroundColorV.split(",");
        backgroundSetting.setColor(ArrayUtilities.parse(colorSplits, Integer.class));
        textBoxSetting.setBackgroundSetting(backgroundSetting);

        //设置文本框前景色
        String textBoxForegroundColorV = p.getProperty("textbox.foreground.color", "205,205,205");
        colorSplits = textBoxForegroundColorV.split(",");
        textBoxSetting.setForeground(ArrayUtilities.parse(colorSplits, Integer.class));
        //获取文本框字体风格
        String textBoxFontStyleV = p.getProperty("textbox.font.style", String.valueOf(Font.PLAIN));

        //设置文本框字体名称
        String textBoxFontNameV = p.getProperty("textbox.font.name", "黑体");
        fontSetting.setFont(new Font(textBoxFontNameV,Integer.valueOf(textBoxFontStyleV),Integer.valueOf(textBoxFontSizeV)));
        textBoxSetting.setFontSetting(fontSetting);

        //设置文本框透明度
        String textBoxOpacityV = p.getProperty("textbox.opacity", "0.8");
        textBoxSetting.setOpacity(Float.valueOf(textBoxOpacityV));
        store(SettingsDialog.SETTING_CONF,"textbox.opacity", String.valueOf(Float.valueOf(textBoxOpacityV)));

        // 加载翻译API密钥设置
        String baiduAppId = p.getProperty("baidu.appId", "");
        String baiduSecurityKey = p.getProperty("baidu.securityKey", "");
        keySetting.getBaidu().setAppId(baiduAppId);
        keySetting.getBaidu().setSecurityKey(baiduSecurityKey);
        
        String youdaoAppKey = p.getProperty("youdao.appKey", "");
        String youdaoAppSecret = p.getProperty("youdao.appSecret", "");
        keySetting.getYoudao().setAppKey(youdaoAppKey);
        keySetting.getYoudao().setAppSecret(youdaoAppSecret);
        
        String deepseekApiKey = p.getProperty("deepseek.apiKey", "");
        keySetting.getDeepseek().setApiKey(deepseekApiKey);
        // 同步到工具类中，方便直接使用
        DeepSeekUtils.API_KEY = deepseekApiKey;
        
        String qianfanApiKey = p.getProperty("qianfan.apiKey", "");
        String qianfanSecretKey = p.getProperty("qianfan.secretKey", "");
        keySetting.getQianfan().setApiKey(qianfanApiKey);
        keySetting.getQianfan().setSecretKey(qianfanSecretKey);
        // 同步到工具类中，方便直接使用
        QianfanUtils.API_KEY = qianfanApiKey;
        QianfanUtils.SECRET_KEY = qianfanSecretKey;
        
        // 同步Baidu和Youdao密钥到工具类
        BaiduUtils.APP_ID = baiduAppId;
        BaiduUtils.APP_SECRET = baiduSecurityKey;
        YoudaoUtils.APP_KEY = youdaoAppKey;
        YoudaoUtils.APP_SECRET = youdaoAppSecret;
        
        // 设置翻译引擎
        String translateEngine = p.getProperty("translate.engine", "deepseek");
        translateSetting = new TranslateSetting();
        translateSetting.setEngine(translateEngine);

        // 设置翻译源语言
        String defaultTranslateSource = null;
        if ("baidu".equals(translateEngine)) {
            defaultTranslateSource = "auto";
        } else if ("youdao".equals(translateEngine)) {
            defaultTranslateSource = "en";
        } else if ("deepseek".equals(translateEngine)) {
            defaultTranslateSource = "auto";
        }
        String translateSource = p.getProperty("translate.source", defaultTranslateSource);
        String translateTarget = p.getProperty("translate.target", "zh");
        if ("baidu".equals(translateEngine)) {
            //设置翻译源语言
            if ("auto".equals(translateSource)) {
                translateSetting.setSource(BaiduUtils.AUTO);
            } else if ("zh".equals(translateSource) || "cn".equals(translateSource)) {
                translateSetting.setSource(BaiduUtils.CHINESE);
            } else if ("en".equals(translateSource)) {
                translateSetting.setSource(BaiduUtils.ENGLISH);
            } else if ("ja".equals(translateSource)) {
                translateSetting.setSource(BaiduUtils.JPANESE);
            } else if ("ko".equals(translateSource)) {
                translateSetting.setSource(BaiduUtils.KOREAN);
            }
            //设置翻译目标语言
            if ("zh".equals(translateTarget) || "cn".equals(translateTarget)) {
                translateSetting.setTarget(BaiduUtils.CHINESE);
            } else if ("en".equals(translateTarget)) {
                translateSetting.setTarget(BaiduUtils.ENGLISH);
            } else if ("ja".equals(translateTarget)) {
                translateSetting.setTarget(BaiduUtils.JPANESE);
            } else if ("ko".equals(translateTarget)) {
                translateSetting.setTarget(BaiduUtils.KOREAN);
            }
        } else if ("youdao".equals(translateEngine)) {
            //设置翻译源语言
            if ("auto".equals(translateSource)) {
                translateSetting.setSource(YoudaoUtils.AUTO);
            }else if ("zh".equals(translateSource) || "cn".equals(translateSource)) {
                translateSetting.setSource(YoudaoUtils.CHINESE);
            } else if ("en".equals(translateSource)) {
                translateSetting.setSource(YoudaoUtils.ENGLISH);
            } else if ("ja".equals(translateSource)) {
                translateSetting.setSource(YoudaoUtils.JPANESE);
            } else if ("ko".equals(translateSource)) {
                translateSetting.setSource(YoudaoUtils.KOREAN);
            }
            //设置翻译目标语言
            if ("zh".equals(translateTarget) || "cn".equals(translateTarget)) {
                translateSetting.setTarget(YoudaoUtils.CHINESE);
            } else if ("en".equals(translateTarget)) {
                translateSetting.setTarget(YoudaoUtils.ENGLISH);
            } else if ("ja".equals(translateTarget)) {
                translateSetting.setTarget(YoudaoUtils.JPANESE);
            } else if ("ko".equals(translateTarget)) {
                translateSetting.setTarget(YoudaoUtils.KOREAN);
            }
        } else if ("google".equals(translateEngine)) {
            //设置翻译源语言
            if ("auto".equals(translateSource)) {
                translateSetting.setSource(GoogleUtils.AUTO);
            } else if ("zh".equals(translateSource) || "cn".equals(translateSource)) {
                translateSetting.setSource(GoogleUtils.CHINESE);
            } else if ("en".equals(translateSource)) {
                translateSetting.setSource(GoogleUtils.ENGLISH);
            } else if ("ja".equals(translateSource)) {
                translateSetting.setSource(GoogleUtils.JPANESE);
            } else if ("ko".equals(translateSource)) {
                translateSetting.setSource(GoogleUtils.KOREAN);
            }
            //设置翻译目标语言
            if ("zh".equals(translateTarget) || "cn".equals(translateTarget)) {
                translateSetting.setTarget(GoogleUtils.CHINESE);
            } else if ("en".equals(translateTarget)) {
                translateSetting.setTarget(GoogleUtils.ENGLISH);
            } else if ("ja".equals(translateTarget)) {
                translateSetting.setTarget(GoogleUtils.JPANESE);
            } else if ("ko".equals(translateTarget)) {
                translateSetting.setTarget(GoogleUtils.KOREAN);
            }
        } else if ("deepseek".equals(translateEngine)) {
            //设置翻译源语言
            if ("auto".equals(translateSource)) {
                translateSetting.setSource(DeepSeekUtils.AUTO);
            } else if ("zh".equals(translateSource) || "cn".equals(translateSource)) {
                translateSetting.setSource(DeepSeekUtils.CHINESE);
            } else if ("en".equals(translateSource)) {
                translateSetting.setSource(DeepSeekUtils.ENGLISH);
            } else if ("ja".equals(translateSource)) {
                translateSetting.setSource(DeepSeekUtils.JPANESE);
            } else if ("ko".equals(translateSource)) {
                translateSetting.setSource(DeepSeekUtils.KOREAN);
            }
            //设置翻译目标语言
            if ("zh".equals(translateTarget) || "cn".equals(translateTarget)) {
                translateSetting.setTarget(DeepSeekUtils.CHINESE);
            } else if ("en".equals(translateTarget)) {
                translateSetting.setTarget(DeepSeekUtils.ENGLISH);
            } else if ("ja".equals(translateTarget)) {
                translateSetting.setTarget(DeepSeekUtils.JPANESE);
            } else if ("ko".equals(translateTarget)) {
                translateSetting.setTarget(DeepSeekUtils.KOREAN);
            }
        } else if ("qianfan".equals(translateEngine)) {
            //设置翻译源语言
            if ("auto".equals(translateSource)) {
                translateSetting.setSource(QianfanUtils.AUTO);
            } else if ("zh".equals(translateSource) || "cn".equals(translateSource)) {
                translateSetting.setSource(QianfanUtils.CHINESE);
            } else if ("en".equals(translateSource)) {
                translateSetting.setSource(QianfanUtils.ENGLISH);
            } else if ("ja".equals(translateSource)) {
                translateSetting.setSource(QianfanUtils.JPANESE);
            } else if ("ko".equals(translateSource)) {
                translateSetting.setSource(QianfanUtils.KOREAN);
            }
            //设置翻译目标语言
            if ("zh".equals(translateTarget) || "cn".equals(translateTarget)) {
                translateSetting.setTarget(QianfanUtils.CHINESE);
            } else if ("en".equals(translateTarget)) {
                translateSetting.setTarget(QianfanUtils.ENGLISH);
            } else if ("ja".equals(translateTarget)) {
                translateSetting.setTarget(QianfanUtils.JPANESE);
            } else if ("ko".equals(translateTarget)) {
                translateSetting.setTarget(QianfanUtils.KOREAN);
            }
        }
    }

    /**
     * 保存配置项到配置文件
     * @param filePath 配置文件路径
     * @param key 配置项键
     * @param value 配置项值
     */
    public static void store(String filePath, String key, String value) {
        try {
            Properties prop = new Properties();
            File file = new File(filePath);

            // 如果文件存在，先加载现有内容
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                prop.load(new InputStreamReader(fis, "UTF-8"));
                fis.close();
            } else {
                // 确保文件目录存在
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            // 输出日志，便于调试
            //System.out.println("保存设置 - 键: " + key + ", 值: " + value);
            
            // 更新或添加新的键值对
            prop.setProperty(key, value);

            // 保存配置文件，使用UTF-8编码
            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            prop.store(osw, "CT Cat Settings");
            osw.close();
            fos.close();
            
            // 验证设置是否保存成功
            FileInputStream verifyFis = new FileInputStream(file);
            Properties verifyProp = new Properties();
            verifyProp.load(new InputStreamReader(verifyFis, "UTF-8"));
            verifyFis.close();
            
            String savedValue = verifyProp.getProperty(key);
            if (savedValue == null || !savedValue.equals(value)) {
                System.err.println("警告: 设置可能未正确保存! 键: " + key + 
                                   ", 期望值: " + value + 
                                   ", 实际值: " + savedValue);
            }
        } catch (Exception e) {
            System.err.println("保存设置失败 - 键: " + key + ", 值: " + value);
            e.printStackTrace();
        }
    }

    /**
     * 获取配置文件的单个值
     * @param settingFilePath
     * @param key
     */
    public static String load(String settingFilePath,String key) throws IOException {
        Properties p = new Properties();
        p.load(new BufferedReader(new InputStreamReader(new FileInputStream(settingFilePath))));
        return p.getProperty(key);
    }
}
